package com.newsvoice.activity;

/**
 * @author Paresh N. Mayani
 * http://www.technotalkative.com
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Activity_Eclair extends DashBoardActivity implements OnPreparedListener {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play_audio);
		Button read = (Button) findViewById(R.id.read);
		read.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new Runnable() {
					public void run() {

						try {
							String sentence = "nguyễn th chủ";
							startStreaming(getApplicationContext(), sentence,
									5028, 216);
							// URL urlTTS = new URL(
							// "http://translate.google.com.vn/translate_tts?ie=UTF-8&q="
							// + sentence.replace(" ", "%20")
							// + "&tl=vi");
							// System.out.println(urlTTS.toString());
							// HttpURLConnection urlConn = (HttpURLConnection)
							// urlTTS
							// .openConnection();
							// urlConn.addRequestProperty("User-Agent",
							// "Mozilla/9.0 (compatible; MSIE 6.0; Windows NT 5.0)");
							// urlConn.setConnectTimeout(5000);
							// InputStream sound = urlConn.getInputStream();
							// System.out.println(sound.available());
							// File tmp = new File("tmp.mp3");
							// FileOutputStream outputStream = new
							// FileOutputStream(
							// tmp);
							// int read = 0;
							// byte[] bytes = new byte[1024];
							//
							// while ((read = sound.read(bytes)) != -1) {
							// outputStream.write(bytes, 0, read);
							// System.out.println(read);
							// }
							//
							// outputStream.close();
							// sound.close();
							// MediaPlayer m = new MediaPlayer();
							// m.setDataSource(tmp.getPath());
							// m.prepare();
							// m.start();
						} catch (Exception e) {
							// TODO: handle exception

						}

						// try {
						// MediaPlayer mediaPlayer = new MediaPlayer();
						// mediaPlayer.setDataSource("http://dl2.org.mp3.zdn.vn/fsdd1131lwwjA/b39e0f9641a978ede9bce2a9aeb21830/51717810/2010/09/25/c/7/c71ef99c00669273f3c21c2931840a26.mp3?filename=Mai%20Mai%20-%20Lam%20Truong.mp3");
						// // setup song from
						// http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
						// URL to mediaplayer data source
						// mediaPlayer.prepare();
						// mediaPlayer.start();
						//
						// } catch (Exception e) {
						//
						// }
					}
				}.run();
			}
		});

	}

	
	public void startStreaming(final Context context, final String text,
			long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
		Runnable r = new Runnable() {
			public void run() {
				try {
					downloadAudioIncrement(context, text);
				} catch (IOException e) {
					Log.e(getClass().getName(),
							"Unable to initialize the MediaPlayer for fileUrl="
									+ text, e);
					return;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		new Thread(r).start();
	}

	/**
	 * Download the url stream to a temporary location and then call the
	 * setDataSource for that local file
	 * 
	 * @throws JSONException
	 */
	public void downloadAudioIncrement(Context context, String text)
			throws IOException, JSONException {
		// String mediaUrl =
		// "http://192.168.5.1:8080/VoiceNewsServer/rest/ttsservices/audio";
		String sentence = "nguyễn thế chủ";
		URL urlTTS = new URL(
		// "http://192.168.5.1/TTSService/Service/service.svc/TTS?voiceIndex=1&rate=0&extension=mp3&text="
		// + sentence.replace(" ", "%20")
				"http://translate.google.com.vn/translate_tts?ie=UTF-8&q="
						+ sentence.replace(" ", "%20") + "&tl=vi");
		HttpURLConnection cn = (HttpURLConnection) urlTTS.openConnection();
		System.out.println(cn.getURL().toString());
		cn.addRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		cn.setConnectTimeout(10000);
		// cn.setRequestProperty("Content-Type", "application/json");
		//
		// ((HttpURLConnection) cn).setRequestMethod("POST");
		// cn.setDoOutput(true);
		// // cn.setDoInput(true);
		// JSONObject data = new JSONObject();
		// data.put("data", text);
		// OutputStreamWriter wr = new OutputStreamWriter(cn.getOutputStream());
		// wr.write(data.toString());
		// wr.close();

		cn.connect();
		// cn.getContent();
		InputStream stream = cn.getInputStream();

		File downloadingMediaFile = new File(context.getCacheDir(),
				"downloadingMedia.dat");

		// Just in case a prior deletion failed because our code crashed or
		// something, we also delete any previously
		// downloaded file to ensure we start fresh. If you use this code,
		// always delete
		// no longer used downloads else you'll quickly fill up your hard disk
		// memory. Of course, you can also
		// store any previously downloaded file in a separate data cache for
		// instant replay if you wanted as well.
		if (downloadingMediaFile.exists()) {
			downloadingMediaFile.delete();
		}

		FileOutputStream out = new FileOutputStream(downloadingMediaFile);
		byte buf[] = new byte[16384];
		int totalBytesRead = 0, incrementalBytesRead = 0;
		do {
			int numread = stream.read(buf);
			if (numread <= 0)
				break;
			out.write(buf, 0, numread);
			totalBytesRead += numread;
			incrementalBytesRead += numread;
			System.out.println(totalBytesRead);
		} while (true);
		stream.close();
		out.close();
		FileInputStream fis = new FileInputStream(downloadingMediaFile);

		MediaPlayer m = new MediaPlayer();
		m.setDataSource(fis.getFD());
		// m.setDataSource(downloadingMediaFile.getPath());
		m.setOnPreparedListener(this);
		m.prepareAsync();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		mp.start();
	}
}
